const path = require('path')
const fs = require('fs')
const { ApiError } = require('../utils/error')

// 文件类型限制
const MIME_TYPES = {
  logo: 'image/png',
  favicon: 'image/x-icon',
  loginBackground: 'image/jpeg',
  loginLogo: 'image/png'
}

// 文件大小限制 (bytes)
const SIZE_LIMITS = {
  logo: 2 * 1024 * 1024, // 2MB
  favicon: 2 * 1024 * 1024, // 2MB
  loginBackground: 5 * 1024 * 1024, // 5MB
  loginLogo: 2 * 1024 * 1024 // 2MB
}

// 删除文件
exports.deleteFile = async (req, res) => {
  const { type } = req.params
  
  if (!MIME_TYPES[type]) {
    throw new ApiError(400, '无效的文件类型')
  }

  const ext = type === 'favicon' ? '.ico' : 
             type === 'loginBackground' ? '.jpg' : '.png'
  const filename = `${type}${ext}`
  const filePath = path.join(__dirname, '../uploads/system', filename)

  try {
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath)
    }

    res.json({
      code: 0,
      message: '删除成功'
    })
  } catch (error) {
    throw new ApiError(500, '文件删除失败')
  }
}

exports.uploadFile = async (req, res) => {
  try {
    console.log('开始处理文件上传请求:', {
      files: req.files,
      body: req.body
    })

    if (!req.files || !req.files.file) {
      throw new ApiError(400, '请选择要上传的文件')
    }

    const { type } = req.body
    const file = req.files.file

    console.log('文件信息:', {
      type,
      filename: file.name,
      size: file.size,
      mimetype: file.mimetype
    })

    // 验证文件类型
    if (!MIME_TYPES[type] || file.mimetype !== MIME_TYPES[type]) {
      const typeMap = {
        'logo': 'PNG图片',
        'favicon': 'ICO图标',
        'loginBackground': 'JPG图片',
        'loginLogo': 'PNG图片'
      }
      throw new ApiError(400, `文件类型错误，${type}只支持${typeMap[type]}格式`)
    }

    // 验证文件大小
    if (file.size > SIZE_LIMITS[type]) {
      const sizeLimit = SIZE_LIMITS[type] / (1024 * 1024)
      throw new ApiError(400, `文件大小超出限制，${type}最大支持${sizeLimit}MB`)
    }

    // 生成文件名
    const ext = path.extname(file.name)
    const filename = `${type}${ext}`
    const uploadPath = path.join(__dirname, '../uploads/system', filename)

    console.log('准备保存文件:', {
      filename,
      uploadPath,
      exists: fs.existsSync(path.dirname(uploadPath))
    })

    try {
      // 确保目录存在
      const dir = path.dirname(uploadPath)
      if (!fs.existsSync(dir)) {
        console.log('创建目录:', dir)
        fs.mkdirSync(dir, { recursive: true })
      }

      // 移动文件
      console.log('开始移动文件...')
      await file.mv(uploadPath)
      console.log('文件移动成功')

      // 返回文件URL
      res.json({
        code: 0,
        data: {
          url: `/api/uploads/system/${filename}`
        }
      })
    } catch (error) {
      console.error('文件处理错误:', {
        error: error,
        message: error.message,
        stack: error.stack,
        code: error.code
      })
      if (error.code === 'EACCES') {
        throw new ApiError(400, '服务器权限不足，无法保存文件')
      } else if (error.code === 'ENOSPC') {
        throw new ApiError(400, '服务器存储空间不足')
      } else if (error.code === 'ENOENT') {
        throw new ApiError(400, '服务器上传目录不存在或无法创建')
      } else {
        throw new ApiError(400, `文件上传失败: ${error.message}`)
      }
    }
  } catch (error) {
    console.error('上传处理错误:', {
      error: error,
      message: error.message,
      stack: error.stack,
      code: error.code
    })
    if (error instanceof ApiError) {
      throw error
    } else {
      throw new ApiError(400, error.message || '文件上传失败')
    }
  }
} 